package sample.one.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import sample.one.model.Foo;
import sample.one.model.Shop;
import sample.one.service.FooService;
import sample.one.service.ShopService;

public class DefaultShopService implements ShopService {
	private JdbcTemplate jdbcTemplate; 
	private FooService fooService;
	
	@Override
	public Shop getShop(String shopName) {
		Shop shop = (Shop) this.jdbcTemplate.queryForObject(
			    "select id, name from shop where name = ?",
			    new Object[]{new String(shopName)},
			    new RowMapper() {
			        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			        	Shop shop = new Shop();
			        	shop.setId(rs.getInt("id"));
			        	shop.setName(rs.getString("name"));
			            return shop;
			        }
			    });
		
		return shop;
	}

	@Override
	public Shop getShop(int id) {
		Shop shop = (Shop) this.jdbcTemplate.queryForObject(
			    "select id, name from shop where id = ?",
			    new Object[]{new Integer(id)},
			    new RowMapper() {
			        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			        	Shop shop = new Shop();
			        	shop.setId(rs.getInt("id"));
			        	shop.setName(rs.getString("name"));
			            return shop;
			        }
			    });
		
		return shop;
	}

	@Override
	public void insertShop(Shop shop) {
		
//		Foo foo = new Foo();
//		foo.setName(shop.getName());
//		fooService.insertFoo(foo);
//		
//		this.jdbcTemplate.update(
//		        "insert into shop (name) values (?)", 
//		        new Object[] {shop.getName()});
		
		this.jdbcTemplate.update(
		        "insert into shop (name) values (?)", 
		        new Object[] {shop.getName()});
	}

	@Override
	public void updateShop(Shop shop) {
		throw new UnsupportedOperationException();
	}

	public FooService getFooService() {
		return fooService;
	}

	public void setFooService(FooService fooService) {
		this.fooService = fooService;
	}

	public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

	@Override
	public void clear() {
		this.jdbcTemplate.update("delete from shop;");
	}
}
